const { completedTestModel } = require("../models/completedTestModel");
const { completedQuestionsModel } = require("../models/completedQuestionsModel");
const { testModel } = require("../models/testModel");

//找到用户的某场考试信息（前端考试结果页面渲染标题，分数）；
async function getTestInfo(req, res, next){
    let {test_id,user_id}=req.query;
    let result=await completedTestModel.find({test_id,user_id});
    if(result.length>0){
        let testInfo=await completedQuestionsModel.find({test_id,user_id}).populate('test_id').populate('questions_id');
        let testPopulate=(await testModel.find({_id:test_id}).populate('KnowledgePointId').populate('TypeId'))[0];
        let title=""+testPopulate.StayTime+testPopulate.Title+testPopulate.KnowledgePointId.KnowledgePoint+testPopulate.TypeId.examType;
        let testScore=0;
        let allScore=0;
        testInfo.map((t)=>{
            let num=Number(t.questions_id.score);
            allScore+=num;
            if(t.user_answer==t.questions_id.RightKey){
                testScore+=num;
            }
        });
        //考试完成信息添加到完成考试数据库中
        await completedQuestionsModel.create({score:testScore,test_id,user_id});
        res.send({
            title,
            testScore,
            allScore,
            code:200
        })
    }else{
        res.send({
            message:"未找到该考生考试信息",
            code:-1
        })
    }
};

//排行榜接口，找到所有完成考试信息
async function getCompletedTest(req, res, next){
    let result=await completedTestModel.find({}).populate('user_id');
    res.send({result})
}

module.exports={getTestInfo,getCompletedTest}